﻿using AutoMapper;
using Enter.Admin.Dtoes;
using Enter.Admin.Entities;
using Enter.Admin.Enums;
using Enter.Admin.Filters;
using Enter.Admin.Models;
using Enter.Admin.Models.DataTables;
using Enter.Admin.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Enter.Admin.Controllers
{
    [TypeFilter(typeof(ActionFilter))]
    public class AttachmentController : BaseController
    {
        private readonly IConfiguration _configuration;
        private readonly Upload _upload;

        public AttachmentController(ILogger<SettingController> logger, IFreeSql fsql, IMapper mapper, IConfiguration configuration, Upload upload) : base(logger, fsql, mapper)
        {
            _configuration = configuration;
            _upload = upload;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index([FromBody] DataTablesParameters<AttachmentSearchModel> model)
        {
            var data = _fsql.Select<Attachment>()
                .Where(t => t.ObjectType == model.Data.ObjectType && t.ObjectId == model.Data.ObjectId && !t.IsDeleted)
                .Count(out var total).Skip(model.Start).Take(model.Length)
                .ToList();
            return Json(new DataTablesResult<Attachment>(model.Draw, total, total, data));
        }

        [HttpPost]
        public ActionResult Index2(long id, long objectId)
        {
            if (id > 0)
            {
                var count = _fsql.Update<Attachment>()
                .Set(a => a.UpdateTime, DateTime.Now)
                .Set(a => a.IsDeleted, true)
                .Where(a => a.Id == id).ExecuteAffrows();
                if (count == 0)
                {
                    return Json(new ResponseResult<string>(false, "删除失败."));
                }
            }
            var data = _fsql.Select<Attachment>().Where(t => t.ObjectType == (int)EnumAttachmentObjectType.档案附件 && t.ObjectId == objectId && !t.IsDeleted).ToList();
            return Json(new ResponseResult<object>(true, data.Select(t=>new { t.Id,t.Name, CatalogTypeName = ((EnumAttachmentCatalogType)t.CatalogType).ToString()}).ToList(), "ok."));
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Upload([FromForm] string objectIds, [FromForm] EnumAttachmentObjectType objectType, [FromForm] int catalogType, IEnumerable<IFormFile> files)
        {
            if (files.Count() == 0) return Json(new ResponseResult<string>(false, "请选择文件."));
            var isTemp = EnumAttachmentObjectType.临时文件 == objectType;
            var result = new List<long>();
            var session = Session();
            foreach (var form_file in files)
            {
                var isSync = false;
                // 写入文件;
                var new_file = FileIO.CreateFile(form_file.FileName, isTemp);
                using (var stream = new_file.FileInfo.Create())
                {
                    form_file.CopyTo(stream);
                }
                if (EnumAttachmentObjectType.档案附件 == objectType) 
                {
                    isSync = _upload.PutObject(new_file.PathName, new_file.FileInfo);
                }
                foreach (var objectId in objectIds.Split(",", StringSplitOptions.RemoveEmptyEntries).Select(t=>long.Parse(t))) 
                {
                    // 写入数据库;
                    var db_att = new Attachment
                    {
                        ObjectType = (int)objectType,
                        ObjectId = objectId,
                        IsTemp = isTemp,
                        CatalogType = catalogType,
                        Catalog = string.Empty,
                        Name = form_file.FileName,
                        PathName = new_file.PathName,
                        Extension = new_file.Extension,
                        FileSize = new_file.FileInfo.Length,
                        FileMD5 = FileIO.Md5(new_file.FileInfo),
                        // 同步文件;
                        IsSync = isSync,
                        CreateUserId = session.Id,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        IsDeleted = false
                    };
                    var att_id = _fsql.Insert<Attachment>(db_att).ExecuteIdentity();
                    result.Add(att_id);
                }
            }
            return Json(new ResponseResult<List<long>>(true, result, "上传成功."));
        }

        [HttpPost]
        public ActionResult Delete(long id)
        {
            var count = _fsql.Update<Attachment>()
                .Set(a => a.UpdateTime, DateTime.Now)
                .Set(a => a.IsDeleted, true)
                .Where(a => a.Id == id).ExecuteAffrows();
            return Json(new ResponseResult<string>(true, "删除成功."));
        }
    }
}
